<template>
  <div class="container">
    <div class="header">
      <h2>课程管理系统</h2>
      <div>
        <el-button
          type="primary"
          @click="
            showAddDialog = true;
            isEditMode = false;
          "
          >新增</el-button
        >
        <el-button type="success" @click="showSearchDialog = true"
          >查找</el-button
        >
      </div>
    </div>

    <div class="table-container">
      <div class="table-wrapper">
        <el-table :data="list" border stripe style="width: 100%; height: 70vh">
          <el-table-column
            v-for="(label, prop) in formPropMap"
            :key="prop"
            :prop="prop"
            :label="label"
          />
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button @click="handleUpdate(scope.row.courseId)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                @click="handleDelete(scope.row.courseId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="params.page"
            v-model:page-size="params.size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- // TODO: 查询功能暂未实现 -->
      <!-- 查找课程 -->
      <el-dialog v-model="showSearchDialog" width="30%" title="查找课程">
        <el-form :model="updateForm" label-width="15%">
          <el-form-item label="课程id">
            <el-input
              v-model="updateForm.courseId"
              placeholder="请输入课程id"
            />
          </el-form-item>
          <el-form-item label="课程名">
            <el-input
              v-model="updateForm.courseName"
              placeholder="请输入课程名"
            />
          </el-form-item>
          <el-form-item label="课程类型">
            <el-select v-model="updateForm.courseType">
              <el-option
                v-for="item in courseTypeArr"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="学分">
            <el-input-number
              v-model="updateForm.credit"
              style="width: 100%"
              :min="0.5"
              :max="20"
              :step="0.5"
              placeholder="请输入学分"
            />
          </el-form-item>
          <el-form-item label="学时">
            <el-input-number
              v-model="updateForm.hours"
              style="width: 100%"
              :min="1"
              :max="100"
              placeholder="请输入学时"
            />
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              v-model="updateForm.description"
              type="textarea"
              maxlength="100"
              placeholder="请输入描述"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="btn-group">
            <el-button @click="showSearchDialog = false">取消</el-button>
            <el-button type="primary" @click="handleSearch">查找</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 修改/添加课程 -->
      <el-dialog
        v-model="showAddDialog"
        :title="isEditMode ? '修改课程信息' : '添加课程'"
        width="30%"
      >
        <el-form :model="updateForm" label-width="15%">
          <el-form-item label="课程id">
            <el-input
              v-model="updateForm.courseId"
              placeholder="请输入课程id"
            />
          </el-form-item>
          <el-form-item label="课程名">
            <el-input
              v-model="updateForm.courseName"
              placeholder="请输入课程名"
            />
          </el-form-item>
          <el-form-item label="课程类型">
            <el-select v-model="updateForm.courseType">
              <el-option
                v-for="item in courseTypeArr"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="学分">
            <el-input-number
              v-model="updateForm.credit"
              style="width: 100%"
              :min="0.5"
              :max="20"
              :step="0.5"
              placeholder="请输入学分"
            />
          </el-form-item>
          <el-form-item label="学时">
            <el-input-number
              v-model="updateForm.hours"
              style="width: 100%"
              :min="1"
              :max="100"
              placeholder="请输入学时"
            />
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              v-model="updateForm.description"
              type="textarea"
              maxlength="100"
              placeholder="请输入描述"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="btn-group">
            <el-button
              @click="
                showAddDialog = false;
                isEditMode = false;
              "
              >取消</el-button
            >
            <el-button v-if="isEditMode" type="primary" @click="update"
              >修改</el-button
            >
            <el-button v-else type="primary" @click="handleAdd">添加</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="showDeleteDialog" title="删除课程" width="30%">
        <span>确定要删除课程 {{ deleteId }} 吗？</span>
        <template #footer>
          <el-button
            @click="
              showDeleteDialog = false;
              deleteId = '';
            "
            >取消</el-button
          >
          <el-button type="danger" @click="deleteCourse">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { courseApi } from "@/api";
import type { CourseType } from "@/types/api-types";
import { ElMessage } from "element-plus";
import { onMounted, reactive, ref } from "vue";

const showAddDialog = ref(false);
const showSearchDialog = ref(false);

// 分页相关
interface PageParams {
  page: number;
  size: number;
}

type CourseForm = {
  courseId: string;
  courseName: string;
  credit: number;
  hours: number;
  courseType: CourseType;
  description: string;
};

/**
 * 属性名称映射表
 */
const formPropMap = {
  courseId: "课程号",
  courseName: "课程名",
  credit: "学分",
  hours: "学时",
  courseType: "课程类型",
  description: "描述"
};

// 课程类型数组
const courseTypeArr: CourseType[] = [
  "专业必修",
  "专业选修",
  "公共必修",
  "公共选修"
];

// 表格
const list = ref<CourseForm[]>([]);
// 数据总数
const total = ref(0);
// 分页请求参数
const params = ref<PageParams>({
  page: 1,
  size: 10
});

// 更新、添加、查找三用表单
const updateForm = reactive<CourseForm>({
  courseId: "",
  courseName: "",
  credit: 0,
  hours: 0,
  courseType: "公共必修",
  description: ""
});

// 更新课程id
const editId = ref<string>("");
// 编辑模式状态
const isEditMode = ref(false);

/**
 * 处理更新
 * @param id 课程id
 */
const handleUpdate = async (id: string) => {
  try {
    // 切换到编辑模式
    isEditMode.value = true;
    // 更新需要修改的课程id
    editId.value = id;
    // 获取该课程信息
    const course = await courseApi.getById(id);
    // 填写信息到表单
    Object.assign(updateForm, course.data);
    // 打开修改弹窗
    showAddDialog.value = true;
  } catch (error) {
    ElMessage.error("课程获取失败");
    console.error("课程获取失败：", error);
  }
};

/**
 * 更新课程
 */
const update = async () => {
  try {
    await courseApi.update(editId.value, updateForm);
    ElMessage.success("课程更新成功");
  } catch (error) {
    ElMessage.error("课程更新失败");
    console.error("课程更新失败：", error);
  } finally {
    // 重置表单
    Object.assign(updateForm, {
      courseId: "",
      courseName: "",
      credit: 0,
      hours: 0,
      courseType: "公共必修",
      description: ""
    });
    // 关闭更新窗口
    showAddDialog.value = false;
    // 重置编辑id
    editId.value = "";
    // 关闭编辑模式
    isEditMode.value = false;
    // 刷新
    getList();
  }
};

/**
 * 新增课程
 */
const handleAdd = async () => {
  try {
    // 发送请求
    await courseApi.create(updateForm);
    ElMessage.success("添加成功");
  } catch (error) {
    ElMessage.error("添加失败");
    console.error("删除失败：", error);
  } finally {
    // 关闭新增窗口
    showAddDialog.value = false;
    // 置空新增表单信息
    Object.assign(updateForm, {
      courseId: "",
      courseName: "",
      credit: 0,
      hours: 0,
      courseType: "公共必修",
      description: ""
    });
    // 刷新
    getList();
  }
};

const showDeleteDialog = ref(false);
// 需要删除的课程id
const deleteId = ref("");

const handleDelete = async (id: string) => {
  deleteId.value = id;
  // 打开删除弹窗
  showDeleteDialog.value = true;
};

/**
 * 删除课程
 */
const deleteCourse = async () => {
  try {
    if (!deleteId.value) {
      throw new Error("无效删除信息");
    }

    // 发出删除申请
    await courseApi.delete(deleteId.value);
    ElMessage.success("删除成功");
  } catch (error) {
    ElMessage.error("删除失败");
    console.error("删除失败：", error);
  } finally {
    // 关闭删除弹窗
    showDeleteDialog.value = false;
    // 重置删除id，防止误删
    deleteId.value = "";
    // 刷新
    getList();
  }
};

const handleSearch = async () => {
  try {
  } catch (error) {
    ElMessage.error("查找失败");
    console.error("查找失败：", error);
  } finally {
  }
};

/**
 * 处理每页大小变化
 * @param val 每页大小
 */
const handleSizeChange = (val: number) => {
  params.value.size = val;
  params.value.page = 1;
  getList();
};

/**
 * 处理页面切换
 * @param val 页号
 */
const handleCurrentChange = (val: number) => {
  params.value.page = val;
  getList();
};

/**
 * 获取表格
 */
const getList = async () => {
  try {
    const res = await courseApi.getPage({
      page: params.value.page - 1,
      size: params.value.size
    });
    list.value = res.data.content || [];
    total.value = res.data.totalElements || 0;
  } catch (error) {
    ElMessage.error("表格获取失败");
    console.error("表格获取失败：", error);
  }
};

onMounted(async () => {
  await getList();
});
</script>

<style lang="css">
.container {
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-shrink: 0;

  h2 {
    margin: 0;
    color: #303133;
  }
}

.table-container {
  flex: 1;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-wrapper {
  flex: 1;
  overflow-y: auto;
}

.pagination {
  flex-shrink: 0;
  background: white;
  padding: 10px 0;
}

.btn-group {
  display: flex;
  justify-content: space-between;
  /* align-items: center; */
  /* width: 80%; */
}
</style>
